package HomeWork;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;

public class UserLoginSystem {
    private static HashMap<String, String> users = new HashMap<>();
    private static HashMap<String, Integer> failAttempts = new HashMap<>();
    private static HashMap<String, Long> lockTime = new HashMap<>();
    private static final int MAX_ATTEMPTS = 3;
    private static final int LOCK_DURATION = 30000; // 30秒

    public static void main(String[] args) {
        // 读取文件中的用户名和密码
        try (BufferedReader br = new BufferedReader(new FileReader("src/HomeWork/user.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split("=");
                users.put(parts[0], parts[1]);
            }
        } catch (IOException e) {
            System.out.println("shujucuowu");
            return;
        }

        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.print("请输入用户名: ");
            String username = scanner.nextLine();

            if (!users.containsKey(username)) {
                System.out.println("用户名不存在。");
                continue;
            }

            // 检查是否被锁定
            if (lockTime.containsKey(username)) {
                long currentTime = System.currentTimeMillis();
                if (currentTime < lockTime.get(username)) {
                    long waitingTime = lockTime.get(username) - currentTime;
                    System.out.println("该用户已被锁定，请" + waitingTime / 1000 +"秒后再试。");
                    continue;
                } else {
                    lockTime.remove(username);
                    System.out.println(failAttempts);
                }
            }

            System.out.print("请输入密码: ");
            String password = scanner.nextLine();

            if (users.get(username).equals(password)) {
                System.out.println("登录成功！");
                failAttempts.put(username, 0); // 重置失败次数
            } else {
                System.out.println("密码错误。");

                int attempts = failAttempts.getOrDefault(username, 0) + 1;
                failAttempts.put(username, attempts);

                if (attempts >= MAX_ATTEMPTS) {
                    long currentTime = System.currentTimeMillis();
                    if (attempts == MAX_ATTEMPTS) {
                        lockTime.put(username, currentTime + LOCK_DURATION);
                        System.out.println("该用户已被锁定30秒。");
                    }
                    if (attempts == MAX_ATTEMPTS*2){
                        System.out.println("该用户已被永久冻结。");
                        lockTime.put(username,currentTime + LOCK_DURATION* 31104000L);
                    }
                }
            }
        }
    }
}